package cn.wzx.controller;

import cn.wzx.entity.*;
import cn.wzx.respJson.RespJson;
import cn.wzx.respJson.Token;
import cn.wzx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin // 允许跨域访问
@Controller
@RequestMapping("/api/public")
public class PublicController {
    @Autowired
    HotService hotService;
    @Autowired
    BookService bookService;
    @Autowired
    UserService userService;
    @Autowired
    LargefileService largefileService;
    @Autowired
    BookTypeService bookTypeService;
    @Autowired
    CartService cartService;

    // 轮播图功能
    @ResponseBody
    @RequestMapping({"/findHot/{num}/{type}"})
    public Map<String, Object> findHot(@PathVariable("num") int num, @PathVariable("type") int type) {
        List<Hot> lst = hotService.findByType(type, num);
        return RespJson.pack(200, "", lst);
    }

    // 根据条件模糊查询，前端传来一个key值进行查询，有分页功能
    @ResponseBody
    @RequestMapping({"/book/findIf/{start}/{num}"})
    public Map<String, Object> findBookIf(@PathVariable("start") Integer start, @PathVariable("num") Integer num, String key) {
        System.out.println("key=" +key);
        if ("".equals(key)) return RespJson.pack(100, "输入不能为空", null);
        List<Book> lst = bookService.findIf(key, start, num);
        // 根据key值查询到的总页数
        int total = bookService.findIfCount(key);
        Map<String, Object> map = new HashMap<>();
        map.put("books", lst);
        map.put("total", total);
        return RespJson.pack(200, "", map);
    }

    // 查询书本分页功能，如果前端有传来书本的类型，则还会根据书本类型进行查询，前端书本详情书本类型分类分页查询功能
    @ResponseBody
    @RequestMapping({"/findBookByPage/{start}/{num}/{typeid}"})
    public Map<String, Object> findBookByPage(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        System.out.println("typeid===" + typeid);
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = this.bookService.findByPageTypeId(start, num, typeid);
        map.put("books", lst);
        // 根据类型ID查询后的总页数
        int count = this.bookService.countTypeId(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    // 图片显示功能
    @ResponseBody
    @RequestMapping({"/showImg/{id}"})
    public void showImg(@PathVariable("id") String id, HttpServletResponse response) {
        byte[] buf;
        if (id == null) return;
        Largefile byId = largefileService.findById(id);
        try {
            buf = (byte[]) byId.getContent();
        }catch (NullPointerException e){
            buf = new byte[1];
        }
        try {
            response.setContentType("image/jpeg");
            response.getOutputStream().write(buf);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 添加到购物车  根据书本的id
    @ResponseBody
    @RequestMapping("/addCart/{bookid}")
    public Map<String, Object> addCart(@PathVariable("bookid") Integer bookid) {
        System.out.println("bookid======" + bookid);
        // 获取到登录后的token，从中获取到登录者的信息，从而获取到用户ID
        MyUser user = (MyUser)Token.getUser();
        if (user == null) return RespJson.pack(401, "你未登录，请登录",null);
        int uid = user.getId();
        // 定义一个购物车接收数据，添加到购物车数量变为1
        Cart cart = new Cart();
        cart.setBookid(bookid);
        cart.setUid(uid);
        cart.setNum(1);
        cartService.addCart(cart);
        return RespJson.pack(200, "加入购物车成功", null);
    }

    // 类型全查询
    @ResponseBody
    @RequestMapping({"/type/findAll"})
    public Map<String, Object> findAll() {
        List<BookType> lst = this.bookTypeService.findAll();
        return RespJson.pack(200, "", lst);
    }

    // 根据书本ID对书本进行点赞
    @ResponseBody
    @RequestMapping({"/book/addRate/{bookid}"})
    public Map<String, Object> addRate(@PathVariable("bookid") Integer bookid) {
        bookService.addRate(bookid);
        return RespJson.pack(200, "点赞成功", null);
    }

    // 查询点赞量前五的书本
    @ResponseBody
    @RequestMapping({"/book/findRate5"})
    public Map<String, Object> findRate5() {
        List<Book> lst = this.bookService.findRate5();
        return RespJson.pack(200, "", lst);
    }

    // 查询销量前五的书本
    @ResponseBody
    @RequestMapping({"/book/findSale5"})
    public Map<String, Object> findSale5() {
        List<Book> lst = this.bookService.findSale5();
        return RespJson.pack(200, "", lst);
    }

    // 查询添加到购物车前五的书本
    @ResponseBody
    @RequestMapping({"/book/findFav5"})
    public Map<String, Object> findFav5() {
        List<Book> lst = this.bookService.findFav5();
        return RespJson.pack(200, "", lst);
    }

    // 分页查找书本信息并按照点赞从高到低排序, 并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping({"/findBookByPageRate/{start}/{num}/{typeid}"})
    public Map<String, Object> findBookByPageRate(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = bookService.findPageRate(start, num, typeid);
        map.put("books", lst);
        int count = bookService.countTypeId(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    //分页查找书本信息并按照销量从高到低排序, 并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping({"/findBookByPageSale/{start}/{num}/{typeid}"})
    public Map<String, Object> findPagesSale_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = this.bookService.findPageSale(start, num, typeid);
        map.put("books", lst);
        int count = this.bookService.countTypeId(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    //分页查找书本信息并按照购物车从高到低, 并且可按照类型(typeid==0 时, 类型查询不生效)
    @ResponseBody
    @RequestMapping({"/findBookByPageFav/{start}/{num}/{typeid}"})
    public Map<String, Object> findPagesFav_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = this.bookService.findPageFav(start, num, typeid);
        map.put("books", lst);
        int count = this.bookService.countTypeId(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    // 添加新用户，默认添加个P，用于新用户添加
    @ResponseBody
    @RequestMapping({"/addUser"})
    public Map<String, Object> addUser(MyUser user, Largefile largefile, @RequestParam(value = "pic",required = false) MultipartFile file) {
        System.out.println("file============" + file);
        if (file == null) {
            return RespJson.pack(500,"图片未上传",null);
        }
        if (file != null && file.getSize()>0){
            try {
                String uuid = UUID.randomUUID().toString();
                user.setImg(uuid);
                largefile.setId(uuid);
                largefile.setFilename(file.getOriginalFilename());
                largefile.setContent(file.getBytes());
                largefileService.add(largefile);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        // 默认添加个P，用于新用户添加
        user.setRole("P");
        user.setClosed(0);
        userService.addUser(user);
        return RespJson.pack(200, "注册新用户成功",null);
    }
}
